package com.net.wanjian.networkhospitalmanager.activity;

import android.graphics.Color;
import android.graphics.drawable.PaintDrawable;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ExpandableListView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.net.wanjian.networkhospitalmanager.R;
import com.net.wanjian.networkhospitalmanager.activity.base.BaseActivity;
import com.net.wanjian.networkhospitalmanager.adapter.RotateOrderExpandableAdapter;
import com.net.wanjian.networkhospitalmanager.adapter.RotateYearAdapter;
import com.net.wanjian.networkhospitalmanager.adapter.base.BaseFragmentPagerListAdapter;
import com.net.wanjian.networkhospitalmanager.bean.SearchMainRotateTeacherResult;
import com.net.wanjian.networkhospitalmanager.bean.SearchRotateStudentInfoListResult;
import com.net.wanjian.networkhospitalmanager.consts.ErrorCodeReturn;
import com.net.wanjian.networkhospitalmanager.fragment.rotateorder.RotateTeacherDoctorInfoFragment;
import com.net.wanjian.networkhospitalmanager.net.HttpUtil;
import com.net.wanjian.networkhospitalmanager.netstatus.NetUtils;
import com.net.wanjian.networkhospitalmanager.utils.DateUtil;
import com.net.wanjian.networkhospitalmanager.utils.ProgressDialogUtils;
import com.net.wanjian.networkhospitalmanager.utils.SharedXmlUtil;
import com.net.wanjian.networkhospitalmanager.view.LPopupWindow;
import com.zhy.autolayout.utils.AutoUtils;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import io.reactivex.observers.DisposableObserver;

public class TotateOrderActivity extends BaseActivity {


    @BindView(R.id.top_back_layout)
    LinearLayout topBackLayout;
    @BindView(R.id.totate_order_year_layout)
    LinearLayout totateOrderYearLayout;
    @BindView(R.id.totate_order_viewpager)
    ViewPager totateOrderViewpager;
    @BindView(R.id.totate_order_expandable_list)
    ExpandableListView totateOrderExpandableList;
    @BindView(R.id.viewpager_tag_viewgroup)
    LinearLayout viewpagerTagViewgroup;
    @BindView(R.id.totate_order_year_image_iv)
    ImageView totateOrderYearImageIv;
    @BindView(R.id.totate_order_top_layout)
    RelativeLayout totateOrderTopLayout;
    @BindView(R.id.totate_order_year_text_tv)
    TextView totateOrderYearTextTv;

    private LPopupWindow mLPopupWindow;

    private ImageView[] mImageViewArray;

    private RotateOrderExpandableAdapter mRotateOrderExpandableAdapter;
    private List<String> yearList;
    private String currentYearMonth;
    private RotateYearAdapter rotateYearAdapter;
    private int selectItem = 2;

    @Override
    protected void initData() {
        topBackLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                TotateOrderActivity.this.finish();
            }
        });

        totateOrderYearLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //点击效果
//                totateOrderYearImageIv.setBackgroundResource();

                //弹出选择年份popwindow,根据选择的年份发送http请求获取数据
                showSelectYearPop();

            }
        });

        //加载年，当前年前后补两年
        yearList = getCurrentYearData();

        getSearchMainTeacherListHttpRequest();
        getTotateOrderDataHttpRequest(currentYearMonth);
    }

    /**
     * 获取规培导师
     */
    private void getSearchMainTeacherListHttpRequest() {
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        Log.e(TAG, "getSearchMainTeacherListHttpRequest: "+ xmlUtil.getDeviceId()+"=="+xmlUtil.getToken()
                +"=="+xmlUtil.getHospitalId()+"=="+xmlUtil.getUserIdentityId()
                +"=="+xmlUtil.getUserIdentity());
        HttpUtil.searchMainTeacherList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                xmlUtil.getUserIdentityId(), xmlUtil.getUserIdentity(), new DisposableObserver<SearchMainRotateTeacherResult>() {
                    @Override
                    public void onNext(SearchMainRotateTeacherResult searchMainRotateTeacherResult) {
                        Log.e(TAG, "onNext: "+searchMainRotateTeacherResult.toString() );
                        if (searchMainRotateTeacherResult.getResult().equals(ErrorCodeReturn.success + "")) {
                            //加载viewpager数据
                            initViewPager(searchMainRotateTeacherResult.getData().getUserIdentityList());
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        Log.e(TAG, "onError: " );
                    }

                    @Override
                    public void onComplete() {
                        Log.e(TAG, "onComplete: " );
                    }
                });

    }

    private void showSelectYearPop() {
        //显示pop
        mLPopupWindow = new LPopupWindow(this);
        View view = LayoutInflater.from(this).inflate(R.layout.pop_window_rotate_year, null);
        AutoUtils.auto(view);
        ListView popListView = (ListView) view.findViewById(R.id.pop_window_rotate_year_list);

        mLPopupWindow.setContentView(view);
        mLPopupWindow.setBackgroundDrawable(new PaintDrawable(Color.WHITE));
        mLPopupWindow.setFocusable(true);

        rotateYearAdapter = new RotateYearAdapter(this, yearList);
        rotateYearAdapter.setSelectedPosition(selectItem);
        popListView.setAdapter(rotateYearAdapter);

        popListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                mLPopupWindow.dismiss();
                selectItem = position;
                totateOrderYearTextTv.setText(yearList.get(position)+"年");

                //选择年份
                String year = "";

                getTotateOrderDataHttpRequest(yearList.get(position));
            }
        });

        if (mLPopupWindow.isShowing()) {
            mLPopupWindow.dismiss();
        } else {
            mLPopupWindow.showAsDropDown(totateOrderTopLayout, 0, 0, Gravity.RIGHT);
        }


    }

    private List<String> getCurrentYearData() {

        List<String> yearStrings = new ArrayList<>();
        String dateToStr = DateUtil.dateToStr(DateUtil.getDate());


        int year = Integer.parseInt(dateToStr.split("-")[0]);

        currentYearMonth = year+"";
        for (int i = 2; i >= -2; i--) {
            yearStrings.add((year + i+""));
        }

        //加载当前的年月并缓存
        return yearStrings;
    }


    /**
     * 调用轮转接口获取数据
     *
     * @param year
     */
    private void getTotateOrderDataHttpRequest(String year) {
        ProgressDialogUtils.showProgressDialog(this, "", R.string.loading_text);
        SharedXmlUtil xmlUtil = SharedXmlUtil.getInstance();
        HttpUtil.searchRotationSchedulingList(xmlUtil.getDeviceId(), xmlUtil.getToken(), xmlUtil.getHospitalId(),
                xmlUtil.getUserIdentityId(), xmlUtil.getUserIdentity(), year, new DisposableObserver<SearchRotateStudentInfoListResult>() {
                    @Override
                    public void onNext(SearchRotateStudentInfoListResult searchRotateStudentInfoListResult) {
                        Log.e(TAG, "onNext: "+searchRotateStudentInfoListResult.toString() );
                        if (searchRotateStudentInfoListResult.getResult() == ErrorCodeReturn.success) {
                            //加载list数据
                            mRotateOrderExpandableAdapter = new RotateOrderExpandableAdapter(TotateOrderActivity.this,searchRotateStudentInfoListResult.getData().getRotationInfo());
                            totateOrderExpandableList.setAdapter(mRotateOrderExpandableAdapter);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        ProgressDialogUtils.dismissProgressDialog();
                    }

                    @Override
                    public void onComplete() {
                        ProgressDialogUtils.dismissProgressDialog();
                    }
                });

    }

    private void initViewPager(List<SearchMainRotateTeacherResult.DataBean.UserIdentityListBean> userIdentityList) {

        List<Fragment> fragmentList = new ArrayList<>();

        int teacherSize = userIdentityList.size();
        for (int i = 0; i < teacherSize; i++) {
            SearchMainRotateTeacherResult.DataBean.UserIdentityListBean o = userIdentityList.get(i);
            fragmentList.add(RotateTeacherDoctorInfoFragment.getInstance(o));
        }

        totateOrderViewpager.setAdapter(new BaseFragmentPagerListAdapter(getSupportFragmentManager(), fragmentList));
        totateOrderViewpager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

            }

            @Override
            public void onPageSelected(int position) {
                //循环设置当前页的标记图
                for (int i = 0; i < mImageViewArray.length; i++) {
                    mImageViewArray[position].setBackgroundResource(R.mipmap.rotate_circle);
                    if (position != i) {
                        mImageViewArray[i].setBackgroundResource(R.mipmap.rotate_circle2);
                    }
                }
            }

            @Override
            public void onPageScrollStateChanged(int state) {

            }
        });
        //加载tag
        viewpagerTagViewgroup.removeAllViews();
        ImageView imageView = null;
        int size = fragmentList.size();
        mImageViewArray = new ImageView[size];
        for (int i = 0; i < size; i++) {
            imageView = new ImageView(this);
            LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(30, 30);
            layoutParams.setMargins(10, 0, 10, 0);
            imageView.setLayoutParams(layoutParams);
            imageView.setPadding(30, 0, 30, 0);

            mImageViewArray[i] = imageView;
            if (i == 0) {
                imageView.setBackgroundResource(R.mipmap.rotate_circle);
            } else {
                imageView.setBackgroundResource(R.mipmap.rotate_circle2);
            }

            viewpagerTagViewgroup.addView(mImageViewArray[i]);
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_totate_order;
    }

    @Override
    protected void onNetworkConnected(NetUtils.NetType type) {

    }

    @Override
    protected void onNetworkDisConnected() {

    }
}
